/*
 * Copyright 2022 Nightingale Team
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

import React, { useState, useEffect } from 'react';
import _ from 'lodash';
import { Trans, useTranslation } from 'react-i18next';
import { Card, Form, Checkbox, Switch, Space, Select, Tooltip, Row, Col, InputNumber, Input, AutoComplete } from 'antd';
import { PlusCircleOutlined, MinusCircleOutlined, QuestionCircleFilled, RightOutlined, DownOutlined, InfoCircleOutlined } from '@ant-design/icons';
import { getTeamInfoList, getNotifiesList } from '@/services/manage';
import { getAlertRulesCallbacks } from '@/services/warning';
import { getWebhooks } from '@/pages/help/NotificationSettings/services';
import AuthorizationWrapper from '@/components/AuthorizationWrapper';
import { panelBaseProps } from '../../constants';
import TaskTpls from './TaskTpls';
// @ts-ignore
import NotifyExtra from 'plus:/parcels/AlertRule/NotifyExtra';
// @ts-ignore
import NotifyChannelsTpl from 'plus:/parcels/AlertRule/NotifyChannelsTpl';

export default function index({ disabled }) {
  const { t } = useTranslation('alertRules');
  const [contactList, setContactList] = useState<{ key: string; label: string }[]>([]);
  const [notifyGroups, setNotifyGroups] = useState<any[]>([]);
  const [globalFlashdutyPushConfigured, setGlobalFlashdutyPushConfigured] = useState(false);
  const [notifyTargetCollapsed, setNotifyTargetCollapsed] = useState<boolean>(false);
  const [callbacks, setCallbacks] = useState<string[]>([]);
  const notify_channels = Form.useWatch('notify_channels');
  const callbacksValue = Form.useWatch('callbacks');
  const getNotifyChannel = () => {
    getNotifiesList().then((res) => {
      setContactList(res || []);
    });
  };
  const getGroups = async (str) => {
    const res = await getTeamInfoList({ query: str });
    const data = res.dat || res;
    setNotifyGroups(data || []);
  };

  useEffect(() => {
    getGroups('');
    getNotifyChannel();
    getWebhooks().then((res) => {
      const globalFlashdutyPushConfigured = _.some(res, (item) => {
        // TODO 糟糕的设计，需要根据 url pathnam 这种匹配来判断是否配置了 flashduty
        // 2024-03-05 排除掉事件墙的推送
        return _.includes(item.url, '/event/push/alert/n9e') && !_.includes(item.url, '/api/v1/event/push/alert/n9e') && item.enable;
      });
      setGlobalFlashdutyPushConfigured(globalFlashdutyPushConfigured);
      if (globalFlashdutyPushConfigured) {
        setNotifyTargetCollapsed(true);
      }
    });
    getAlertRulesCallbacks().then((res) => {
      setCallbacks(res);
    });
  }, []);

  return (
    <>
      <Card {...panelBaseProps} title={t('notify_configs')} data-oid='msojo6-'>
        <div
          style={{
            display: globalFlashdutyPushConfigured ? 'block' : 'none',
            marginBottom: 8,
            cursor: 'pointer',
          }}
          onClick={() => {
            setNotifyTargetCollapsed(!notifyTargetCollapsed);
          }}
          data-oid='2b0.m73'
        >
          <Space data-oid='5ixfh:7'>
            <span data-oid=':d4d4sf'>{t('notify_flashduty_configured')}</span>
            {notifyTargetCollapsed ? <RightOutlined data-oid='w30_x_t' /> : <DownOutlined data-oid='1cqt2b0' />}
          </Space>
        </div>
        <div
          style={{
            display: notifyTargetCollapsed ? 'none' : 'block',
          }}
          data-oid='-u7oy85'
        >
          <Form.Item
            label={
              <Space data-oid='z509d9o'>
                {t('notify_channels')}
                <a target='_blank' href='https://flashcat.cloud/docs/content/flashcat-monitor/nightingale-v6/usage/alert/alert-notify/' data-oid='ptee.w3'>
                  {t('notify_channels_doc')}
                </a>
              </Space>
            }
            name='notify_channels'
            data-oid='dz9step'
          >
            <Checkbox.Group disabled={disabled} data-oid='w8tc3cg'>
              {contactList.map((item) => {
                return (
                  <Checkbox key={item.label} value={item.key} data-oid='gor_u7:'>
                    {item.label}
                  </Checkbox>
                );
              })}
            </Checkbox.Group>
          </Form.Item>
          <NotifyChannelsTpl contactList={contactList} notify_channels={notify_channels} name={['extra_config', 'custom_notify_tpl']} data-oid='o9z4udc' />
          <Form.Item label={t('notify_groups')} name='notify_groups' data-oid='bdcn77r'>
            <Select mode='multiple' showSearch optionFilterProp='children' data-oid='0_mw7:r'>
              {_.map(notifyGroups, (item) => {
                // id to string 兼容 v5
                return (
                  <Select.Option value={_.toString(item.id)} key={item.id} data-oid='x5uv6i:'>
                    {item.name}
                  </Select.Option>
                );
              })}
            </Select>
          </Form.Item>
        </div>
        <Form.Item label={t('notify_recovered')} data-oid='ofwip3y'>
          <Space data-oid='bo:v1k.'>
            <Form.Item name='notify_recovered' valuePropName='checked' style={{ marginBottom: 0 }} data-oid='g882c9o'>
              <Switch data-oid='.8fh5:o' />
            </Form.Item>
            <Tooltip title={t(`notify_recovered_tip`)} data-oid='37gp6v5'>
              <QuestionCircleFilled data-oid='6i23u2-' />
            </Tooltip>
          </Space>
        </Form.Item>
        <Form.Item shouldUpdate noStyle data-oid='j2_0b_6'>
          {({ getFieldValue }) => {
            return (
              <Row gutter={16} data-oid='ibhzdcg'>
                <Col span={8} data-oid='jjqle8:'>
                  <Form.Item
                    label={t('recover_duration')}
                    name='recover_duration'
                    tooltip={t('recover_duration_tip', { num: getFieldValue('recover_duration') })}
                    data-oid='u0b.t8v'
                  >
                    <InputNumber min={0} style={{ width: '100%' }} data-oid='hkxaw4y' />
                  </Form.Item>
                </Col>
                <Col span={8} data-oid='q2nlpz1'>
                  <Form.Item
                    label={t('notify_repeat_step')}
                    name='notify_repeat_step'
                    rules={[
                      {
                        required: true,
                      },
                    ]}
                    tooltip={t('notify_repeat_step_tip', { num: getFieldValue('notify_repeat_step') })}
                    data-oid='-rjr3cj'
                  >
                    <InputNumber min={1} style={{ width: '100%' }} data-oid='_7t:_29' />
                  </Form.Item>
                </Col>
                <Col span={8} data-oid='jla32ik'>
                  <Form.Item
                    label={t('notify_max_number')}
                    name='notify_max_number'
                    rules={[
                      {
                        required: true,
                      },
                    ]}
                    tooltip={t('notify_max_number_tip')}
                    data-oid='.s13:0p'
                  >
                    <InputNumber min={0} precision={0} style={{ width: '100%' }} data-oid='plwg-sj' />
                  </Form.Item>
                </Col>
              </Row>
            );
          }}
        </Form.Item>
        <AuthorizationWrapper allowedPerms={['/job-tpls']} data-oid='laz0bne'>
          <TaskTpls data-oid='gfoql-b' />
        </AuthorizationWrapper>
        <Form.List name='callbacks' data-oid='71moku4'>
          {(fields, { add, remove }) => (
            <div data-oid='e.eywdc'>
              <Space align='baseline' data-oid='.vqkzqi'>
                {t('callbacks')}
                <Tooltip
                  title={
                    <Trans
                      ns='alertRules'
                      i18nKey='alertRules:callbacks_tip'
                      components={{ a: <a href='https://flashcat.cloud/docs/content/flashcat-monitor/nightingale-v6/faq/go-template/' target='_blank' data-oid='u773sm3' /> }}
                      data-oid='_tk3lw5'
                    />
                  }
                  overlayClassName='ant-tooltip-max-width-600 ant-tooltip-with-link'
                  data-oid='ndzoyzk'
                >
                  <InfoCircleOutlined data-oid='b:5oppj' />
                </Tooltip>
                <PlusCircleOutlined className='control-icon-normal' onClick={() => add()} data-oid='c8a.eg8' />
              </Space>
              {fields.map((field) => (
                <Row gutter={16} key={field.key} data-oid='ob4rmc5'>
                  <Col flex='auto' data-oid='wm0l4-o'>
                    <Form.Item {...field} name={[field.name, 'url']} data-oid='kl0c.in'>
                      <AutoComplete
                        options={_.map(callbacks, (item) => {
                          return {
                            value: item,
                          };
                        })}
                        filterOption={(inputValue, option) => {
                          if (option && option.value && typeof option.value === 'string') {
                            return option.value.indexOf(inputValue) !== -1;
                          }
                          return true;
                        }}
                        data-oid='av1d.94'
                      />
                    </Form.Item>
                  </Col>
                  <Col flex='40px' data-oid='v1us9mi'>
                    <MinusCircleOutlined className='control-icon-normal' onClick={() => remove(field.name)} data-oid='o7rq8hl' />
                  </Col>
                </Row>
              ))}
            </div>
          )}
        </Form.List>
        <div
          style={{
            display: callbacksValue && callbacksValue.length > 0 ? 'block' : 'none',
          }}
          data-oid='hguggme'
        >
          <Space data-oid='mcjzb6o'>
            {t('override_global_webhook')}
            <Tooltip title={t('override_global_webhook_tip')} data-oid='e-h_zy:'>
              <InfoCircleOutlined data-oid='nyphbuy' />
            </Tooltip>
            <Form.Item name={['rule_config', 'override_global_webhook']} valuePropName='checked' noStyle data-oid='_k0n:ro'>
              <Switch data-oid='4rfsgx5' />
            </Form.Item>
          </Space>
        </div>

        <Form.List name='annotations' data-oid='zpwwnc-'>
          {(fields, { add, remove }) => (
            <div data-oid='s9wp-j.'>
              <Space align='baseline' data-oid='81n8rtr'>
                {t('annotations')}
                <PlusCircleOutlined className='control-icon-normal' onClick={() => add()} data-oid='v.hpfbz' />
              </Space>
              {fields.map((field) => (
                <Row gutter={16} key={field.key} data-oid='7nxr3:y'>
                  <Col flex='120px' data-oid='90u_iwi'>
                    <Form.Item {...field} name={[field.name, 'key']} data-oid='4ungu12'>
                      <AutoComplete
                        options={[
                          {
                            value: 'recovery_promql',
                          },
                          {
                            value: 'runbook_url',
                          },
                          {
                            value: 'dashboard_url',
                          },
                          {
                            value: 'summary',
                          },
                        ]}
                        style={{ width: 200 }}
                        data-oid='4q1uorc'
                      />
                    </Form.Item>
                  </Col>
                  <Col flex='auto' data-oid='z.48t1s'>
                    <Form.Item {...field} name={[field.name, 'value']} data-oid='uklpfmo'>
                      <Input.TextArea autoSize data-oid='4a10opg' />
                    </Form.Item>
                  </Col>
                  <Col flex='40px' data-oid='kk00wmx'>
                    <MinusCircleOutlined className='control-icon-normal' onClick={() => remove(field.name)} data-oid='2ky0g00' />
                  </Col>
                </Row>
              ))}
            </div>
          )}
        </Form.List>
      </Card>
      <NotifyExtra contactList={contactList} notifyGroups={notifyGroups} data-oid='l0xjpg7' />
    </>
  );
}
